package com.situ.company.employee.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.json.JSONObject;

import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.employee.service.EmployeeService;
import com.situ.company.util.Upload;

@WebServlet("/EmployeeUploadServlet")
public class EmployeeUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private EmployeeService service = new EmployeeService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, Object> map = null;
        try {
            map = Upload.upload(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        String code = map.get("code").toString();
        EmployeeModel dbmodel = service.selectModel(new EmployeeModel(code));
        Upload.delFile(dbmodel.getImage());

        List<String> list = (List<String>) map.get("list");
        String image = list.get(0);

        EmployeeModel modelSession = (EmployeeModel) request.getSession().getAttribute("user");
        if (modelSession.getCode().equals(code)) {
            modelSession.setImage(image);
            request.getSession().setAttribute("user", modelSession);
        }

        EmployeeModel model = new EmployeeModel(code);
        model.setImage(image);
        service.updateImage(model);

        Map<String, String> res = new HashMap<>();
        res.put("code", "0");
        res.put("data", image);
        response.getWriter().print(new JSONObject(res).toString());
    }

}
